<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">
          <el-form-item label="会议主题">
            <el-input v-model="listQuery.meetingTitle"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>
          <el-form-item label="参会人员">
            <el-input v-model="listQuery.meetingUserName"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>
          <el-form-item label="申请会议室名称">
            <el-input v-model="listQuery.meetingName"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>

        </div>
        <div class="right-box">
          <el-button size="mini"
                     @click="handleFilter">查询
          </el-button>
          <el-button size="mini"
                     @click="reset" type="info">重置
          </el-button>
          <el-button size="mini"
                     type="success" @click="handleCreate">新增
          </el-button>
        </div>
      </template>
    </search-box>


    <div class="table-wrap">
      <el-table :data="list"
                style="width:100%"
                element-loading-text="Loading"
                height="600">
        <el-table-column
          type="index"
          width="50"
          label="序号"
        ></el-table-column>

        <el-table-column prop="departmentName"
                         label="申请部门名称">
        </el-table-column>

        <el-table-column prop="departmentCode"
                         label="申请部门编码">
        </el-table-column>
        <el-table-column prop="userName"
                         label="申请员工姓名">
        </el-table-column>
        <el-table-column prop="userCode"
                         label="申请员工工号">
        </el-table-column>

        <el-table-column prop="meetingCode"
                         label="会议室门牌号">
        </el-table-column>

        <el-table-column prop="meetingName"
                         label="会议室名称">
        </el-table-column>

        <el-table-column prop="meetingTitle"
                         label="会议主题">
        </el-table-column>
        <el-table-column prop="meetingUserName"
                         label="参会人员">
        </el-table-column>

        <el-table-column prop="applyStartTime"
                         label="申请开始时间">
        </el-table-column>
        <el-table-column prop="applyEndTime"
                         label="申请结束时间">
        </el-table-column>


        <el-table-column prop="isApproval"
                         label="是否批准">
        </el-table-column>


        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList"/>
    </div>


    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      style="margin-top: -5%"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="150px">

        <el-form-item label="申请会议室门牌号" prop="meetingCode">

          <el-select v-model="form.meetingCode"
                     placeholder="请选择申请会议室门牌号" @change="getMeetingRoomList1">
            <el-option v-for="item in meetingRoomList"
                       :key="item.meetingCode"
                       :label="item.meetingCode"
                       :value="item.meetingCode">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="申请会议室名称" prop="meetingName">
          <el-select v-model="form.meetingName"
                     placeholder="请选择申请会议室名称" @change="getMeetingRoomList2">
            <el-option v-for="item in meetingRoomList"
                       :key="item.meetingCode"
                       :label="item.meetingName"
                       :value="item.meetingCode">
            </el-option>
          </el-select>

        </el-form-item>


        <el-form-item label="会议主题" prop="meetingTitle">
          <el-input v-model="form.meetingTitle"></el-input>
        </el-form-item>


        <el-form-item label="参会人员部门" prop="departmentName">
          <el-select v-model="form.departmentName" @change="getUsersList"
                     placeholder="请选择部门">
            <el-option v-for="item in departmentList"
                       :key="item.departmentName"
                       :label="item.departmentName"
                       :value="item.departmentName">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="参会人员">
          <el-select v-model="meetingUserName"
                     placeholder="请选择参会人员" multiple>
            <el-option v-for="item in usersList"
                       :key="item.userCode"
                       :label="item.userName"
                       :value="item.userName">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="申请开始时间">
          <el-col :span="11">
            <el-date-picker type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="form.startDate1"
                            style="width: 100%;"></el-date-picker>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-time-picker value-format="HH:mm:ss" placeholder="选择时间" v-model="form.startDate2"
                            style="width: 100%;"></el-time-picker>
          </el-col>
        </el-form-item>

        <el-form-item label="申请结束时间">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" v-model="form.endDate1"
                            style="width: 100%;"></el-date-picker>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-time-picker placeholder="选择时间" value-format="HH:mm:ss" v-model="form.endDate2"
                            style="width: 100%;"></el-time-picker>
          </el-col>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary" @click="onSubmit">确 定</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import * as apiUser from '@/api/user'
  import * as meetingRoom from '@/api/meeting/meetingRoom'
  import * as meetingApply from '@/api/meeting/meetingApply'
  import * as myProject from '@/api/projectOa/myProject'
  import * as department from '@/api/system-setting/department'
  import * as position from '@/api/system-setting/position'
  import * as user from '@/api/system-setting/user'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import { MessageBox } from 'element-ui'
  import bus from '@/utils/eventBus'
  import searchBox from '@/components/searchBox.vue'

  export default {
    name: 'department',
    components: { Pagination, searchBox },
    directives: { waves },
    filters: {},
    data() {
      return {
        list: null,
        total: 0,
        dialogVisible: false,
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          departmentName: '',
          departmentName1: '',
          departmentCode: '',
          positionName: '',
          roleName: '',
          pageSize: 50,
          name: undefined,
          proPersonLiable: undefined,
          proDepartment: undefined,
          appName: process.env.VUE_APP_APP_NAME,
          tenantIdList: []
        },
        meetingRoomList: [],
        meetingRoomList1: [],

        form: {},

        usersList: [],
        listParent: [],

        departmentList: [],

        dialogTitle: '',
        meetingUserName:null,

        rulesList: [
          { label: '管理员', value: '管理员' },
          { label: '言川一级用户', value: '言川一级用户' },
          { label: '言川二级用户', value: '言川二级用户' },
          { label: '言川三级用户', value: '言川三级用户' }

        ],

        rules: {
          meetingCode: [{ required: true, message: '申请会议室门牌号必选', trigger: 'blur' }],
          meetingName: [{ required: true, message: '申请会议室名称必选', trigger: 'blur' }],
          meetingTitle: [{ required: true, message: '会议主题必填', trigger: 'blur' }]
          // meetingUserName: [{ required: true, message: '参会人员必选', trigger: 'blur' }]

        }
      }
    },
    computed: {
      ...mapGetters([
        'selectedTenantId',
        'tenantList'
      ])
    },
    created() {
      this.getList()
      this.getMeetingRoomList()
      this.getDepartmentList()

      // 监听 租户改变的事件,选择不同租户后,立马刷新数据
      bus.$on('selectedTenantIdChanged', () => {
        console.log('selectedTenantIdChanged事件触发...')
        this.getList()
      })

    },
    mounted() {
      // 测试用
      // var that = this
      // setTimeout(function() {
      //   that.dialogFormVisible = true
      // }, 5000)

      // alert(this.$store.getters.selectedTenantId);
    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      bus.$off('selectedTenantIdChanged')
    },
    methods: {
      async getList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }

        //获取后端数据
        const { content } = await meetingApply.getMeetingApplyInfoList(this.listQuery)
        this.list = content.list
        this.total = content.totalCounts
      },

      async getListParent() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }

        //获取后端数据
        const { content } = await myProject.getProjectListParent(this.listQuery)
        this.listParent = content

      },

      async getDepartmentList() { // 获取列表数据

        const { content } = await department.getDepartmentList(this.listQuery)
        this.departmentList = content.list

      },



      async getMeetingRoomList() { // 获取列表数据

        const { content } = await meetingRoom.getMeetingRoomInfoList(this.listQuery)
        this.meetingRoomList = content.list

      },

      async getMeetingRoomList1() { // 获取列表数据
        this.listQuery.meetingCode = this.form.meetingCode;
        const { content } = await meetingRoom.getMeetingRoomInfoList(this.listQuery)
        this.meetingRoomList1 = content.list
        this.$set(this.form,'meetingName',this.meetingRoomList1[0].meetingName);

      },

      async getMeetingRoomList2() { // 获取列表数据

        this.listQuery.meetingName = this.form.meetingName;
        const { content } = await meetingRoom.getMeetingRoomInfoList(this.listQuery)
        this.meetingRoomList1 = content.list
        this.$set(this.form,'meetingCode',this.meetingRoomList1[0].meetingCode);

      },

      async getRoleList() { // 获取列表数据

        const { content } = await department.getRoleList(this.listQuery)
        this.rulesList = content.list

      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },

      handleCreate() {
        this.form = {}
        this.dialogVisible = true
        this.dialogTitle = '会议室新增'
        this.listQuery = {}
        this.getListParent()
      },
      handleUpdate(row) {
        this.dialogVisible = true
        this.dialogTitle = '会议室编辑'
        this.form = row
        if (row.applyStartTime != null && row.applyStartTime != '') {
          this.form.startDate1 = row.applyStartTime.split(' ')[0]
          this.form.startDate2 = row.applyStartTime.split(' ')[1]
          this.form.endDate1 = row.applyEndTime.split(' ')[0]
          this.form.endDate2 = row.applyEndTime.split(' ')[1]
        }

        this.meetingUserName = this.form.meetingUserName.split(",")
        console.log(this.meetingUserName);
        this.getListParent();
        this.getUsersList();

      },

      handleDelete(row) {
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          meetingApply.deleteMeetingApplyInfo(row.id).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
        })

      },

      reset() {
        this.listQuery.meetingTitle = null
        this.listQuery.meetingUserName = null
        this.listQuery.meetingName = null
        this.getList()
      },
      cancel() {
        this.listQuery.meetingTitle = null
        this.listQuery.meetingUserName = null
        this.listQuery.meetingName = null
        this.dialogVisible = false
        this.getList()
      },
      onSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.form.tenantId = this.$store.getters.selectedTenantId

            this.form.applyStartTime = this.form.startDate1 + ' ' + this.form.startDate2
            this.form.applyEndTime = this.form.endDate1 + ' ' + this.form.endDate2

            let meetingUserNameStr ="" ;

            console.log(this.meetingUserName);
            for(let i= 0 ;i<this.meetingUserName.length;i++){

              meetingUserNameStr+=(this.meetingUserName[i]+',');


            }
            this.form.meetingUserName = meetingUserNameStr.slice(0,meetingUserNameStr.length-1)

            if (this.dialogTitle == '会议室新增') {
              meetingApply.createMeetingApplyInfo(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.listQuery.meetingTitle = null
                  this.listQuery.meetingUserName = null
                  this.listQuery.meetingName = null
                  this.dialogVisible = false
                  this.getList()

                }
              })
            } else if (this.dialogTitle == '会议室编辑') {
              meetingApply.updateMeetingApplyInfo(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.listQuery.meetingTitle = null
                  this.listQuery.meetingUserName = null
                  this.listQuery.meetingName = null
                  this.dialogVisible = false
                  this.getList()

                }
              })
            }

          } else {
            console.log('error submit!!')
            return false
          }
        })

      }
      ,
      async getUsersList() { // 获取列表数据
        this.form.userName = ''
        this.usersList = []
        console.log('this.userName', this.userName)
        const { content } = await user.getUserListNoName(this.form)
        this.usersList = content

      }

    }
  }
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }
</style>
